/*      
 * 模块编号  
 * 功能描述 
 * 文件名 MyRoundRule.java 
 * 作者 王磊 
 * 编写日期 2022年01月16日 
 */
package wl.demo.springcloud.lb;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;

@Component
public class MyRoundRule implements IMyRule{
	@Autowired
	private DiscoveryClient discoveryClient;
	
	private AtomicInteger nextServerCyclicCounter = new AtomicInteger(0);
	
	@Override
	public ServiceInstance getService(String serviceId) {
		if (serviceId == null) {
			return null;
		}
		List<ServiceInstance> serviceInstances = discoveryClient.getInstances(serviceId);
		if (serviceInstances.isEmpty()) {
			return null;
		}
		return getNextService(serviceInstances);
	}

	private ServiceInstance getNextService(
			List<ServiceInstance> serviceInstances) {
		int current = 0;
		int next = 0;
		do {
			current = this.nextServerCyclicCounter.get();
			next = current >= Integer.MAX_VALUE ? 0 : current + 1;
		} while (!nextServerCyclicCounter.compareAndSet(current, next));
		return serviceInstances.get(next % serviceInstances.size());
	}

}
